package com.casems.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.casems.commons.dto.Menus;
import com.casems.commons.execption.ParamExecption;
import com.casems.commons.util.JwtUtil;
import com.casems.commons.util.ValidatorUtil;
import com.casems.commons.vo.LoginVO;
import com.casems.commons.vo.PageVO;
import com.casems.commons.vo.RegisterVO;
import com.casems.commons.vo.ResultVO;
import com.casems.entity.Cases;
import com.casems.entity.User;
import com.casems.mapper.UserRoleMapper;
import com.casems.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tch
 * @since 2023-05-12
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    CasesService casesService;

    @Autowired
    CasesMedicalService casesMedicalService;

    @Autowired
    CasesSymptomService casesSymptomService;

    @PutMapping("/addUser")
    public ResultVO addUser(@RequestBody  User user,@RequestParam(required = false,defaultValue = "3") int roleId) {
        //验证用户名
        if(userService.getUser(user.getPhone())!=null){
            throw new ParamExecption("该手机号已经被使用，请检查后重试",400);
        }
        user.setPassword(SecureUtil.md5(user.getPassword()));
        return userService.addUser(user,roleId)?
                ResultVO.success("添加成功"):ResultVO.failed("添加失败");
    }
    @Transactional
    @DeleteMapping("/deleteById")
    public ResultVO deleteById(@RequestBody int[] ids){
        int count = 0;

        for(int idd : ids) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id",idd);
            userRoleService.remove(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("userid",idd);
            List<Cases> casesList = casesService.list(queryWrapper);

            if(casesList != null && casesList.size()!=0) {
                for (Cases cases : casesList) {
                    queryWrapper.clear();
                    queryWrapper.eq("cases_id", cases.getId());
                    casesMedicalService.remove(queryWrapper);
                    casesSymptomService.remove(queryWrapper);

                }
                queryWrapper.clear();
                queryWrapper.eq("userid", idd);
                casesService.remove(queryWrapper);
            }
            userService.removeById(idd);
            count++;
        }
        return count>=ids.length?ResultVO.success("删除成功"):ResultVO.failed();
    }

    @RequestMapping("/updateUser")
    public ResultVO updateByid(@RequestBody RegisterVO user){

        if(user.getSmsCode()!=null){
            String savedSMSCode = stringRedisTemplate.opsForValue()
                    .get(user.getPhone());

            // 校验验证码
            if(StringUtils.isEmpty(savedSMSCode)){
                throw new ParamExecption("短信验证码过期",400);
            }
            if(!StringUtils.equalsIgnoreCase(savedSMSCode,user.getSmsCode())){
                throw  new ParamExecption("短信验证码错误",400);
            }
        }
        User user1 = userService.getById(user.getId());
        if(!user1.getPassword().equals(user.getPassword())){//当用户密码有变动时，对密码加密
            user.setPassword(SecureUtil.md5(user.getPassword()));
        }
        return userService.updateById(user)?ResultVO.success("修改成功"):ResultVO.failed();
    }

    @PostMapping("/getAllStaff")
    public ResultVO getAllStaff(@RequestParam("pageNumber") int pageNumber,
                                @RequestParam("pageSize") int pageSize,
                                @RequestBody User user){
        PageVO<User> userList = userService.getAllStaff(pageNumber,pageSize,user);
        return userList!=null?
                ResultVO.success(userList):ResultVO.failed();
    }
    @PostMapping("/getAllPatient")
    public ResultVO getAllPatient(@RequestParam("pageNumber") int pageNumber,
                                @RequestParam("pageSize") int pageSize,
                                @RequestBody User user){
        PageVO<User> userList = userService.getAllPatient(pageNumber,pageSize,user);
        return userList!=null?
                ResultVO.success(userList):ResultVO.failed();
    }

    @GetMapping("/getInfo")
    public ResultVO getInfo(@RequestHeader("Authorization") String token){
        String phone = JwtUtil.getPhone(token);
        User user = userService.getUser(phone);
        return user!=null?ResultVO.success(user):ResultVO.failed("用户信息查询失败");
    }


    @RequestMapping("/register")
    public ResultVO register(@RequestBody RegisterVO registerVO){
        String token = userService.register(registerVO) ;
        if(token != null){
            Map<Object, Object> data = MapUtil.builder().put("token", token).build();
            data.put("message","注册成功");
            return ResultVO.success(data);
        }
        return ResultVO.failed("注册失败");
    }

    @RequestMapping("/login")
    public ResultVO login(@RequestBody LoginVO loginVO){
        String token = userService.login(loginVO);
        Map<Object, Object> data = MapUtil.builder().put("token", token).build();
        return ResultVO.success(data);
    }
    @RequestMapping("/loginSms")
    public ResultVO loginSms(@RequestBody LoginVO loginVO){
        String token = userService.loginSms(loginVO);
        Map<Object, Object> data = MapUtil.builder().put("token", token).build();
        return ResultVO.success(data);
    }

    @RequestMapping("/queryMenus")
    public ResultVO queryMenus(@RequestHeader("Authorization") String token){
        try {
            String phone = JwtUtil.getPhone(token);
            User user = userService.getUser(phone);

            List<Menus> menus = userService.getMenusByUserId(user.getId());
            List<Menus> tops = new ArrayList<>();

            menus.forEach(item -> {
                if (item.getPid() == -1) {
                    tops.add(item);
                }
            });
            for(Menus top : tops) {
                userService.setChildren(top, menus);
            }
            return ResultVO.success(tops);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVO.failed("菜单查询失败");
        }
    }
}

